﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace PeopleFinderBusiness
{
	public class UserController
	{
		public int RegisterUser(string clientIP, string plainPassword, string email, string realName, string surnames)
		{
			int createdId = 0;
			DatabaseDataContext bd = new DatabaseDataContext();
			SHA1CryptoServiceProvider csp = new SHA1CryptoServiceProvider();
			byte[] passwordHash = csp.ComputeHash(System.Text.Encoding.UTF8.GetBytes(plainPassword));
			string hashedPassword = System.Text.Encoding.UTF8.GetString(passwordHash);
			try
			{	
				User newUser = new User()
				{
					HashedPassword = hashedPassword,
					Email = email,
					Realname = realName,
					Surnames = surnames
				};
				bd.User.InsertOnSubmit(newUser);
				bd.SubmitChanges();
				Logger.WriteLog(LogTypeEnum.UserCreation, clientIP, string.Format("User created, UserId is {0}", newUser.IdUser), null);
				createdId = newUser.IdUser;
			}catch(Exception exc)
			{
				Logger.WriteLog(LogTypeEnum.ApplicationError, clientIP, string.Format("Unknown error registering user: {0}", exc.Message), null);
			}
			return createdId;
		}

		public bool Login(string clientIP, string userName, string plainPassword)
		{
			bool loggedIn = false;
			DatabaseDataContext bd = new DatabaseDataContext();
			SHA1CryptoServiceProvider csp = new SHA1CryptoServiceProvider();
			byte[] passwordHash = csp.ComputeHash(System.Text.Encoding.UTF8.GetBytes(plainPassword));
			string hashedPassword = System.Text.Encoding.UTF8.GetString(passwordHash);
			try
			{
				User currentUser = (from p in bd.User where p.Email.ToLower() == userName.ToLower() && p.HashedPassword == hashedPassword select p).FirstOrDefault();
				if(currentUser != null) loggedIn = true;
				else
				{
					Logger.WriteLog(LogTypeEnum.UserFailedAutentication, clientIP, string.Format("User failed authentication. User '{0}' ", userName), null);	
				}
			}catch(Exception exc)
			{
				Logger.WriteLog(LogTypeEnum.ApplicationError, clientIP, string.Format("Unknown error login user: {0}", exc.Message), null);
			}
			return loggedIn;
		}
	}
}
